/*
 * ManagerSelector.cpp
 *
 *  Created on: 2013-2-1
 *      Author: Dspark
 */

#include "ManagerSelector.h"
#include <qheaderview.h>

ManagerSelector::ManagerSelector():
selectedModel(0,3),poolModel(0,3),selectionTitle("项目管理人员"), poolTitle("人员列表"),
add2Selection("<<"),add2Pool(">>")
{
	initUI();
}

void ManagerSelector::clearData()
{
	selectedModel.removeRows(0,selectedModel.rowCount());
	poolModel.removeRows(0,poolModel.rowCount());
}

void ManagerSelector::load(User& actor)
{

	clearData();
	QList<QStandardItem*> defaultSelect;
	defaultSelect << new QStandardItem(QString("%1").arg(actor.getId()))
		<< new QStandardItem(actor.getName()) << new QStandardItem(actor.getTypeString());
	selectedModel.appendRow(defaultSelect);

	QSqlDatabase& db = Dao.getDateBase();
	QSqlQuery query(db);
	query.exec(QString("SELECT id,name,type FROM `user` where `id`<>%1 and `locked`=false").arg(actor.getId()));
	QSqlRecord r = query.record();
	int idx_id = r.indexOf("id");
	int idx_name = r.indexOf("name");
	int idx_type = r.indexOf("type");
	while(query.next())
	{
		QList<QStandardItem*> manager;
		manager << new QStandardItem(QString("%1").arg(query.value(idx_id).toUInt()))
		<< new QStandardItem(query.value(idx_name).toString())
		<< new QStandardItem(User::getTypeString((User::Type)query.value(idx_type).toInt()));
		poolModel.appendRow(manager);
	}
}

void ManagerSelector::load(quint32 projectId)
{
	clearData();
	QSqlDatabase& db = Dao.getDateBase();
	QSqlQuery query(db);

	if(query.exec( QString("select uid,uname,utype from projectmanager where pid=%1").arg(projectId) ) )
	{
		QString idlist;
		QSqlRecord r = query.record();
		int idx_id = r.indexOf("uid");
		int idx_name = r.indexOf("uname");
		int idx_type = r.indexOf("utype");
		while(query.next())
		{
			QList<QStandardItem*> manager;
			manager << new QStandardItem(QString("%1").arg(query.value(idx_id).toUInt()))
			<< new QStandardItem(query.value(idx_name).toString())
			<< new QStandardItem(User::getTypeString((User::Type)query.value(idx_type).toInt()));
			selectedModel.appendRow(manager);

			idlist.append( QString("%1,").arg(query.value(idx_id).toUInt()) );
		}

		idlist = idlist.replace(idlist.length()-1, 1, " ");
		qDebug()<<"idlist: "<<idlist;
		if( query.exec( QString("select id,name,type from user where id not in(%1) and locked = false").arg(idlist)) )
		{
			r = query.record();
			idx_id = r.indexOf("id");
			idx_name = r.indexOf("name");
			idx_type = r.indexOf("type");

			while(query.next())
			{
				QList<QStandardItem*> manager;
				manager << new QStandardItem(QString("%1").arg(query.value(idx_id).toUInt()))
				<< new QStandardItem(query.value(idx_name).toString())
				<< new QStandardItem(User::getTypeString((User::Type)query.value(idx_type).toInt()));
				poolModel.appendRow(manager);
			}

		}else{
			qDebug()<<"get other managers fail";
		}

	}

}


void ManagerSelector::initUI()
{
	selected.setEditTriggers(QAbstractItemView::NoEditTriggers);
	pool.setEditTriggers(QAbstractItemView::NoEditTriggers);

	selected.setSelectionBehavior(QAbstractItemView::SelectRows);
	pool.setSelectionBehavior(QAbstractItemView::SelectRows);

	selected.setSelectionMode(QAbstractItemView::MultiSelection);
	pool.setSelectionMode(QAbstractItemView::MultiSelection);

	selected.verticalHeader()->setVisible(false);
	pool.verticalHeader()->setVisible(false);

	selected.horizontalHeader()->setVisible(false);
	pool.horizontalHeader()->setVisible(false);

	selected.setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);

	selected.setModel(&selectedModel);
	pool.setModel(&poolModel);

	selected.setToolTip("双击快速添加到右侧");
	pool.setToolTip("双击快速移回到左侧");


	selected.setColumnHidden(0,true);
	pool.setColumnHidden(0,true);


	connect(&pool,SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(slt_poolDoubleClicked(const QModelIndex &)) );
	connect(&selected,SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(slt_selectionDoubleClicked(const QModelIndex &)) );

	add2Selection.setToolTip("单击将右侧中选中项移动到左侧");
	add2Pool.setToolTip("单击将左侧中选中项移动到右侧");
	buttonLayout.addWidget(&add2Selection,0,Qt::AlignHCenter);
	buttonLayout.addWidget(&add2Pool,0, Qt::AlignHCenter);

	connect(&add2Selection, SIGNAL(clicked()), this, SLOT(slt_2SelectionClicked()) );
	connect(&add2Pool, SIGNAL(clicked()), this, SLOT(slt_2PoolClicked()) );

	selectionLayout.addWidget(&selected);
	selectionLayout.addWidget(&selectionTitle,0,Qt::AlignCenter);
	layout.addLayout(&selectionLayout);

	layout.addLayout(&buttonLayout);

	poolLayout.addWidget(&pool);
	poolLayout.addWidget(&poolTitle,0,Qt::AlignCenter);
	layout.addLayout(&poolLayout);

	this->setLayout(&layout);

}

void ManagerSelector::slt_2SelectionClicked()
{
	QModelIndexList list = pool.selectionModel()->selectedRows();

	if(list.size()<1)
	{
		return;
	}

	QModelIndex first = list.takeFirst();
	QList<int> rows;
	rows.append(first.row());

	while(!list.empty())
	{
		int index = list.takeFirst().row();
		bool uninserted = true;
		for(int i=0; i<rows.size(); i++)
		{
			if(rows.at(i)>index)
			{
				rows.insert(i,index);
				uninserted = false;
				break;
			}
		}
		if(uninserted)
		{
			rows.append(index);
		}
	}


	int remain = selectedModel.rowCount();
	for(int i=rows.size()-1; i>=0; --i)
	{
		selectedModel.insertRow(remain,poolModel.takeRow(rows.at(i)));
	}

	adjustButton();

}

void ManagerSelector::slt_2PoolClicked()
{
	QModelIndexList list = selected.selectionModel()->selectedRows();
	if(list.size()<1)
	{
		return;
	}

	QModelIndex first = list.takeFirst();
		QList<int> rows;
		rows.append(first.row());

		while(!list.empty())
		{
			int index = list.takeFirst().row();
			bool uninserted = true;
			for(int i=0; i<rows.size(); i++)
			{
				if(rows.at(i)>index)
				{
					rows.insert(i,index);
					uninserted = false;
					break;
				}
			}
			if(uninserted)
			{
				rows.append(index);
			}
		}



		int remain = poolModel.rowCount();
		for(int i=rows.size()-1; i>=0; --i)
		{
			poolModel.insertRow(remain,selectedModel.takeRow(rows.at(i)));
		}

		adjustButton();

}

void ManagerSelector::slt_poolDoubleClicked(const QModelIndex &index)
{
	selectedModel.appendRow(poolModel.takeRow(index.row()));
	adjustButton();
}

void ManagerSelector::slt_selectionDoubleClicked(const QModelIndex &index)
{
	poolModel.appendRow(selectedModel.takeRow(index.row()));
	adjustButton();
}

void ManagerSelector::adjustButton()
{
	add2Selection.setEnabled(poolModel.rowCount()>0);
	add2Pool.setEnabled(selectedModel.rowCount()>0);
}

QList<quint32>& ManagerSelector::getSelectedUserId()
{
	selectedId.clear();
	for(int i=0,total = selectedModel.rowCount(); i<total; i++)
	{
		selectedId << selectedModel.item(i,0)->text().toUInt();
	}
	return selectedId;
}

ManagerSelector::~ManagerSelector() {
	// TODO Auto-generated destructor stub
}

